<template>
  <div>
    <div class="box">
      <!-- 头部form表单 -->
      <el-form
        :inline="true"
        :model="formInline"
        class="demo-form-inline form_top"
      >
        <el-form-item label="人员搜索:" style="font-size: 14px">
          <el-input
            v-model="formInline.userName"
            placeholder="请输入"
            style="width: 210px"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            class="formbutton"
            @click="onSubmit"
          >查询</el-button>
        </el-form-item>
      </el-form>
      <!-- form表单下按钮 -->
      <div class="button_top">
        <el-button
          type="primary"
          icon="el-icon-circle-plus-outline"
          class="formbutton buttonbodytop"
          @click="openDialog('add')"
        >新建</el-button>
        <!-- table表格 -->
        <el-table
          :data="tableData"
          style="width: 100%"
          class="table_top"
          :header-cell-style="{ backgroundColor: '#f3f6fb', fontweight: 400 }"
        >
          <el-table-column prop="index" label="序号" width="80px" />
          <el-table-column prop="userName" label="人员名称" align="center" />
          <el-table-column prop="regionName" label="归属区域" align="center" />
          <el-table-column prop="role.roleName" label="角色" align="center" />
          <el-table-column prop="mobile" label="电话" align="center" />
          <el-table-column prop="address" label="操作" align="center">
            <template #default="{ row }">
              <el-button
                type="text"
                @click="openDialog('edit', row)"
              >修改</el-button>
              <el-button
                type="text"
                style="color: #ff5a5a"
                @click="delList(row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="foot">
          <p>
            共{{ totalCount }}条记录 第 {{ formInline.pageIndex }}/{{
              totalPage
            }}
            页
          </p>
          <div v-show="totalCount !== 1" class="foot_button">
            <el-button
              plain
              :class="{
                foot_button_top: true,
                isdis: formInline.pageIndex === 1
              }"
              :disabled="formInline.pageIndex === 1"
              @click="upPage"
            >上一页</el-button>
            <el-button
              plain
              :class="{
                foot_button_foot: true,
                isdis: totalPage === formInline.pageIndex
              }"
              :disabled="totalPage === formInline.pageIndex"
              @click="nextPage"
            >下一页</el-button>
          </div>
        </div>
      </div>
    </div>
    <!-- 弹窗 -->
    <el-dialog
      :title="diologTitle"
      :visible.sync="showDialog"
      width="40%"
      @close="closeDialog"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <el-form-item label="人员名称" prop="userName">
          <el-input
            v-model="form.userName"
            placeholder="请选择"
            maxlength="5"
            show-word-limit
            style="width: 480px"
          />
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-select
            v-model="form.roleId"
            placeholder="请选择"
            style="width: 480px"
          >
            <el-option
              v-for="item in role"
              :key="item.roleId"
              :label="item.roleName"
              :value="item.roleId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="联系电话" prop="mobile">
          <el-input
            v-model="form.mobile"
            placeholder="请输入"
            maxlength="11"
            show-word-limit
            style="width: 480px"
          />
        </el-form-item>
        <el-form-item label="负责区域" prop="regionId">
          <el-select
            v-model="form.regionId"
            placeholder="请选择"
            style="width: 480px"
          >
            <el-option
              v-for="item in region"
              :key="item.id"
              :label="item.remark"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="头像" prop="image">
          <el-upload
            v-model="form.image"
            class="avatar-uploader"
            action=""
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            :http-request="UploadImg"
          >
            <img v-if="form.image" :src="form.image" class="avatar">
            <i v-else class="el-icon-upload avatar-uploader-icon" />
          </el-upload>
          <div style="color: #bac0cd">
            支持扩展名：jpg、png，文件不得大于100kb
          </div>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-checkbox v-model="form.status">是否启用</el-checkbox>
        </el-form-item>
        <div class="dialog-footer">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button type="primary" @click="addOrEdit">确 定</el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
import {
  getPersonnelList,
  getRoleList,
  getRegionList,
  addPersonnelList,
  detailPersonnelList,
  updatePersonnelList,
  removePersonnelList
} from '@/api/personnel'

export default {
  name: 'Tektor',
  data() {
    return {
      tableData: [],
      formInline: {
        pageIndex: 1,
        pageSize: 10,
        userName: null,
        region: null
      },
      totalCount: '',
      totalPage: '',
      titleType: 'add',
      showDialog: false,
      form: {
        userName: null,
        roleId: null,
        mobile: null,
        regionId: null,
        regionName: null,
        status: null,
        image: null
      },
      rules: {
        userName: [
          { required: true, message: '请输入人员名称', trigger: 'blur' }
        ],
        roleId: [{ required: true, message: '请输入角色', trigger: 'blur' }],
        mobile: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          {
            pattern: /^1[1-9]\d{9}$/,
            message: '手机号格式不正确',
            trigger: 'blur'
          }
        ],
        regionId: [
          { required: true, message: '请输入负责区域', trigger: 'blur' }
        ],
        status: null,
        image: [{ required: true, message: '请上传', trigger: 'blur' }]
      },
      id: '',
      role: '',
      region: ''
    }
  },
  computed: {
    diologTitle() {
      if (this.titleType === 'add') return '新增人员'
      if (this.titleType === 'edit') return '编辑人员'
      return '新增人员'
    }
  },
  async created() {
    this.initData()
    // 角色
    const data = await getRoleList()
    console.log(data)
    this.role = data
    // 区域
    const { currentPageRecords } = await getRegionList({
      pageIndex: 1,
      pageSize: 100000
    })
    console.log(currentPageRecords)
    this.region = currentPageRecords
  },
  methods: {
    onSubmit() {
      this.initData()
    },
    // 数据
    async initData() {
      const data = await getPersonnelList(this.formInline)
      data.currentPageRecords = data.currentPageRecords.map((item, index) => {
        const indexs = (this.formInline.pageIndex - 1) * 10 + index + 1
        const obj = { index: indexs }
        item = { ...obj, ...item }
        return item
      })
      console.log(data)
      this.tableData = data.currentPageRecords
      this.totalCount = data.totalCount
      this.totalPage = data.totalPage
    },
    // 上一页
    upPage() {
      this.formInline.pageIndex--
      if (this.formInline.pageIndex < 1) {
        this.formInline.pageIndex = 1
      }
      this.initData()
    },
    // 下一页
    nextPage() {
      this.formInline.pageIndex++
      if (this.formInline.pageIndex >= this.totalPage) {
        this.formInline.pageIndex = this.totalPage
      }
      this.initData()
    },
    beforeAvatarUpload(file) {
      const isJPG = ['image/jpeg', 'image/png'].includes(file.type)
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过100kb!')
      }
      return isJPG && isLt2M
    },
    // 上传头像
    UploadImg(data) {
      console.log(data)
      // 密钥
      const cos = new COS({
        SecretId: 'AKIDSqDSUJ7mDPLILMqQDyqcrzxmXSSPbm4H',
        SecretKey: 'KPPOIE6ztd9hAYtBXizynvx5HRabUEkb'
      })
      // 完成cos对象的初始化
      //  cos.putObject(参数，发请求后的回调函数)
      cos.putObject(
        {
          Bucket: 'zcy-1318643425', // 存储桶名称
          Region: 'ap-nanjing', // 地域名称
          Key: data.file.name, // 文件名称
          StorageClass: 'STANDARD', // 固定值
          Body: data.file // 文件对象
        },
        (err, data) => {
          if (err) {
            this.$message.error(err.Message)
          }
          if (data.statusCode === 200 && data.Location) {
            this.form.image = 'https://' + data.Location
          }
          console.log(data)
        }
      )
    },
    // 新增打开
    async openDialog(type, row) {
      this.titleType = type
      if (type === 'edit') {
        this.id = row.id
        const data = await detailPersonnelList(row.id)
        console.log(data)
        this.form = data
        this.form.image = data.image
        console.log(this.form.image)
      }
      this.showDialog = true
    },
    // 取消
    closeDialog() {
      this.form = {
        userName: null,
        roleId: null,
        mobile: null,
        regionId: null,
        regionName: null,
        status: null,
        image: null
      }
      this.$refs.form.resetFields()
      this.showDialog = false
    },
    // 确定按钮 新增修改
    async addOrEdit() {
      try {
        await this.$refs.form.validate()
        if (this.titleType === 'add') {
          this.form.regionName = this.region.find(
            item => item.id === this.form.regionId
          ).remark
          console.log(this.form.regionName)
          const data = await addPersonnelList(this.form)
          console.log(data)
        }
        if (this.titleType === 'edit') {
          await updatePersonnelList({ id: this.id, ...this.form })
        }
        this.closeDialog()
        this.initData()
        if (this.titleType === 'add') {
          this.$message({
            message: '添加成功',
            type: 'success',
            offset: 80
          })
        } else {
          this.$message({
            message: '修改成功',
            type: 'success',
            offset: 80
          })
        }
      } catch (error) {
        this.$message({
          message: '请填入必填项',
          type: 'success',
          offset: 80
        })
      }
    },
    // 删除
    async delList(id) {
      await removePersonnelList(id)
      this.initData()
      this.$message({
        message: '删除成功',
        type: 'success',
        offset: 80
      })
    }
  }
}
</script>

<style scoped lang="scss">
.box {
  margin: 10px 15px 0 15px;
  .demo-form-inline.form_top {
    // height: 60px;
    background-color: #fff;
    padding-top: 11px;
    padding-left: 20px;
    ::v-deep .el-form-item__label {
      font-weight: normal;
    }
    .formbutton {
      background-color: #5f84ff;
    }
  }
  .button_top {
    margin-top: 15px;
    background-color: #fff;
    padding-left: 15px;
    padding-top: 15px;
    margin-bottom: 15px;
    .buttonbodytop {
      border: 0px;
      background-color: #ff883a;
    }
    .buttonbodyfoot {
      border: 0px;
      background-color: #fbf4f0;
      color: #655b56;
    }
    .table_top {
      margin-top: 15px;
    }
    .foot {
      display: flex;
      justify-content: space-between;

      margin-top: 40px;
      padding-left: 15px;
      padding-right: 15px;
      padding-bottom: 30px;
      p {
        color: #dbdfe5;
      }
      .foot_button {
        height: 30px;
        line-height: 30px;
        .foot_button_top {
          margin-right: 15px;
          border: 0px;
          background-color: #d5ddf8;
          color: #606266;
        }
        .foot_button_foot {
          border: 0px;
          background-color: #d5ddf8;
          color: #606266;
        }
        .isdis {
          background-color: #edf0f9 !important;
          color: #d8dde6 !important;
        }
      }
    }
  }
}

.el-form {
  margin-left: 20px;
  ::v-deep .el-form-item__label {
    font-weight: normal;
  }
  .avatar-uploader {
    width: 115px;
    height: 115px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    background-color: #f3f6fb;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    text-align: center;
    width: 115px;
    line-height: 115px;
  }
  .avatar {
    width: 115px;
    height: 115px;
    display: block;
  }
  .dialog-footer {
    margin-top: 20px;
    text-align: center;
    margin-right: -20px;
    .el-button--default {
      background-color: #fbf4f0 !important;
      border: 1px solid #fbf4f0;
      color: #2d2c2c;
      margin-left: -20px;
      margin-right: 20px;
    }
    .el-button--primary {
      background-color: #ff5e20 !important;
      border: 1px solid #ff5e20;
    }
  }
}
::v-deep  .el-dialog__title {
    font-size: 16px;
    font-weight: 700;
    color: #333;
  }
</style>
